package com.hongyun.tms.infra;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author liPeng
 * @date 2024-06-06
 */
@Component
public class RedisUtils {

    public static RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 添加分布式锁
     */
    public static <T> Boolean setNxCacheObject(final String key, final T value, long lt, TimeUnit tu) {
        return redisUtils.redisTemplate.opsForValue().setIfAbsent(key, value, lt, tu);
    }

    @PostConstruct
    public void init() {
        redisUtils = this;
    }

    // ====================公共====================

    /**
     * 设置key-value（不设置过期时间）
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean set(String key, Object value) {
        try {
            redisUtils.redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置key-value（设置过期时间）
     *
     * @param key
     * @param value
     * @param timeout 过期时间
     * @return
     */
    public static boolean set(String key, Object value, long timeout, TimeUnit timeUnit) {
        try {
            if (timeout > 0) {
                redisUtils.redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取key的值
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        Object result = null;
        try {
            result = redisUtils.redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除key
     *
     * @param key 可以传一个key或多个key
     */
    public static void delKey(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisUtils.redisTemplate.delete(key[0]);
            } else {
                redisUtils.redisTemplate.delete(Arrays.asList(key));
            }
        }
    }
}
